package com.csaba.connector.axa;

import java.util.logging.Logger;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.csaba.connector.ServiceException;
import com.csaba.connector.axa.model.AXABank;
import com.csaba.connector.axa.model.AXASession;
import com.csaba.connector.model.Session;
import com.csaba.connector.service.AbstractLoginService;
import com.csaba.connector.service.AccountHistoryService;
import com.csaba.connector.service.AccountService;
import com.csaba.util.LoggerHelper;

/**
 * XXX implement ChangePasswordService in AXA
 * 
 * @author Gabe
 */
public class AXALoginService extends AbstractLoginService implements Codes
{
	@SuppressWarnings( "unused" )
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	@Override
	public void execute( final Session nullSession ) throws ServiceException
	{
		if ( customer == null )
			throw new ServiceException("Login service is not correctly initialized.");
		if ( nullSession != null )
			throw new ServiceException("Session is already initialized. Cannot login again in the same session.");

		session = new AXASession();
		final AXASession axa = (AXASession) session;

		//load login page for session ID
		final NameValuePair[] loginData = new NameValuePair[] {// 
		new BasicNameValuePair("UserName", customer.getLoginId()),//
				new BasicNameValuePair("Password", customer.getPassword()), // 
		};

		final String loginResult = axa.doPost(AXASession.getRequestURL(REQUEST_VERIFY_USERID), loginData);
		axa.debugFile("loginResult", loginResult);

		AXAUtil.checkForHTMLError(loginResult, "err.loginFailed");

		//save customer details
		this.session.setCustomer(customer);
		customer.setId(customer.getLoginId());
		customer.setBank(AXABank.getInstance());
		customer.setName("[AXA Customer - " + customer.getLoginId() + "]");

		//permissions
		customer.addPermission(AccountService.PERMISSION);
		customer.addPermission(AccountHistoryService.PERMISSION);
	}

}
